<template>
	<view class="page">
		<template v-if="scrollTop<=450">
			<view class="backBox" :style="{top:menuTop+'px'}">
				<view class="Vr" style="padding: 10rpx;border-radius: 100%;">
					<u-icon name='arrow-left' color='#fff' @click='$utils.back()' size='30rpx' />
				</view>
			</view>
			<view @click="changeimage" v-if="myUser.id==detail.user_id&&!loading"
				:style="{top:menuTop+'px',right:menuRight+20+'px',height:menuHeight+'px'}" class="VrBox">
				<view class="Vr" style="border-radius: 100%;padding: 10rpx;">
					<text class="icon-tupian iconfont" style="margin-right: 0;" />
				</view>
			</view>
		</template>
		<u-navbar v-else title="挑战详情" border @leftClick="$utils.back()" placeholder>
		</u-navbar>
		<view style="flex: 1;">
			<z-paging ref="paging" style="height: 100%;" :fixed="false" v-model="List" @query="query"
				:default-page-no="1" :hide-empty-view='true' :default-page-size="10" :auto="false" @scroll='scroll'>
				<view class="background">
					<image mode="aspectFill"  :src="detail.thumb" class="masking"
						style="z-index:1;background: transparent;"></image>
					<view class="masking" v-if="!loading" />
					<view class="masking" v-else />
					<view class="userBox" :style="{top:menuTop+80+'px'}">
						<u-avatar mode='aspectFill' :src='user.avatar' size='100rpx' @click.stop='jumpUser(user.id)' />
						<view style="width: 20rpx;"></view>
						<view style="flex: 1;">
							<u-text :lines='1' :text='user.nick_name' color='#fff' />
							<view style="height: 20rpx;"></view>
							<view style="display: flex;">
								<view>
									<u--text lines='1' :iconStyle='{color:"#fff"}' prefixIcon='map' color='#fff'
										:text='detail.title' size='24rpx' />
								</view>
							</view>
						</view>
					</view>
					<view class="Followed viewWidth" v-if="!loading">
						<view @click.stop="Followed" class="Vr ">
							<u-icon v-if="!isFollowed" color='#fff' labelColor='#fff' name="heart" size="24rpx"
								labelSize='28rpx' label='关注'></u-icon>
							<u-icon v-else color='#fff' labelColor='#fff' name="heart-fill" size="24rpx"
								labelSize='28rpx' label='取消关注'></u-icon>
						</view>
						<view @click.stop="Thumbsup" class="Vr ">
							<u-icon v-if="!isThumbsuped" color='#fff' labelColor='#fff' name="thumb-up" size="24rpx"
								labelSize='28rpx' label='点赞'></u-icon>
							<u-icon v-else color='#fff' labelColor='#fff' name="thumb-up-fill" size="24rpx"
								labelSize='28rpx' label='取消点赞'></u-icon>
						</view>
						<view style="flex: 1;" class="startBox">
							距离{{detail.start_at}}还剩下{{daysBetween(detail.start_at)}}天
						</view>
					</view>
					<view class="radius" />
				</view>

				<view class="viewWidth InfoBox">
					<view class="title">
						<u-icon name="attach" size="40rpx" labelSize='24rpx' label='目标信息'></u-icon>
					</view>
					<view class="infoContent" v-if='loading'>
						<view style="width: 50%;">
							<view class="mb20">
								<view style="height: 30rpx;width: 80%;" class="Skeleton" />
							</view>
							<view class="mb20">
								<view style="height: 30rpx;width: 80%;" class="Skeleton" />
							</view>
						</view>
						<view style="width: 50%;">
							<view class="mb20">
								<view style="height: 30rpx;width: 80%;" class="Skeleton" />
							</view>
							<view class="mb20">
								<view style="height: 30rpx;width: 80%;" class="Skeleton" />
							</view>
						</view>
					</view>
					<view class="infoContent " v-else>
						<view style="width: 50%;">
							<view class="mb20">
								<u--text lines='1' size='24rpx' :text='`目标减重：${detail.weight}Kg`' />
							</view>
							<view class="mb20">
								<u--text lines='1' size='24rpx' :text='`天数：${detail.days}天`' />
							</view>
						</view>
						<view style="width: 50%;">
							<view class="mb20">
								<u--text lines='1' size='24rpx' :text='`开始日期：${detail.start_at}`' />
							</view>
							<view class="mb20">
								<u--text lines='1' size='24rpx' :text='`参加人数：${detail.user_count}`' />
							</view>
						</view>
					</view>
				</view>
				<view class="viewWidth InfoBox">
					<view class="title">
						<u-icon name="attach" size="40rpx" labelSize='24rpx' label='参加用户'></u-icon>
					</view>
					<user :list='List' :loading='Listloading' />
				</view>
			</z-paging>
			<view v-if="!loading&&is_public&&myUser.id!=detail.user_id" class="add" @click="attended">
				<u-icon name='plus' color='#fff' labelColor='#fff' :label='isAttended?"退出活动":"参加活动"' labelSize='24rpx'
					size='28rpx' />
			</view>
		</view>
		<root-portal>
			<u-modal :show="AttendedAddShow" :showCancelButton='true' @close='cancel' @cancel='cancel'
				@confirm='confirm'>
				<view style="width: 100%;">
					<view class="popupTitle">
						<u-icon name='close' color='#fff' />
						<view>
							加入挑战
						</view>
						<u-icon name='close' @click='cancel' />
					</view>
					<view style="padding: 0 40rpx;">
						<u--form labelWidth='100' labelPosition="top" :model="form" :rules="rules" ref="uForm">
							<u-form-item label="体重:" prop="weight" borderBottom>
								<u--input v-model="form.weight" placeholder="请输入体重,注意单位为Kg" />
							</u-form-item>
							<u-form-item label="想说的话:" prop="motto" borderBottom>
								<u--input v-model="form.motto" placeholder="请输入想说的话" />
							</u-form-item>
						</u--form>
					</view>
				</view>
			</u-modal>
		</root-portal>
	</view>
</template>

<script>
	import ranking from './components/ranking'
	import user from './components/user'
	import active from './components/active'
	export default {
		components: {
			ranking,
			active,
			user
		},
		data() {
			return {
				is_public: false,
				has_started: true,
				isThumbsuped: false,
				myUser: uni.getStorageSync('user'),
				isFollowed: false,
				Listloading: true,
				userList: [],
				AttendedAddShow: false,
				isAttended: false,
				List: [],
				detail: {},
				loading: true,
				menuHeight: 0,
				menuRight: 0,
				conquer_id: 0,
				menuTop: 0,
				scrollTop: 0,
				user: {},
				token: uni.getStorageSync('token'),
				form: {
					weight: null,
					motto: null
				},
				rules: {
					'weight': [{
						required: true,
						message: '请输入体重',
						trigger: ['blur', 'change']
					}, {
						type: 'number',
						message: '请输入正确体重',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return value > 0
						},
						message: '体重必须大于0',
						trigger: ['blur', 'change']
					}],
					'motto': {
						type: 'string',
						required: true,
						message: '请输入想说的话',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		onShareAppMessage() {
		
			return {
				title: this.detail.title,
				path: '/Conquer/detailNoStar?id=' + this.conquer_id,
				imageUrl: this.detail.thumb
			};
		},
		//2.分享到朋友圈
		onShareTimeline() {
			return {
				title: this.detail.title,
				path: '/Conquer/detailNoStar?id=' + this.conquer_id,
				imageUrl: this.detail.thumb
			};
		},
		onLoad(op) {
			this.conquer_id = op.id
			this.getDateil(op.id)
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect() //可以获取小程序胶囊的位置。
			this.menuTop = menuButtonInfo.top
			this.menuRight = menuButtonInfo.width
			this.menuHeight = menuButtonInfo.height
			let res = uni.getSystemInfoSync()
		},
		methods: {
			// 判断是否授权微信订阅消息
			auditSubscriptionsSetting() {
				let that = this
				const tmplId = 'TJmlYKB_ncZ0ddRd71K92w1dGq1RvEE7v1aHzba-eIA'
				wx.getSetting({
					withSubscriptions: true,
					success(res) {
						console.log(res)
						if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
							if (
								res.subscriptionsSetting.itemSettings &&
								res.subscriptionsSetting.itemSettings[tmplId]
							) {
								let item = res.subscriptionsSetting.itemSettings[tmplId]
								if (item == 'reject') {
									console.log('提示：用户拒绝订阅消息')
									that.dingyueComfirm(tmplId)
								} else if (item == 'accept') {
									console.log('提示：您已经开启订阅消息')
									that.dingyueComfirm(tmplId)
								} else if (item == 'ban') {
									console.log('提示：您已经被后台封禁')
								}
							} else {
								console.log('提示：用户没有勾选订阅消息或者没有状态')
								that.dingyueComfirm(tmplId)
							}
						} else {
							console.log('提示：订阅消息主开关没打开')
							wx.showModal({
								title: '订阅消息',
								content: '您当前拒绝接受消息通知，是否去开启',
								confirmText: '开启授权',
								confirmColor: '#345391',
								cancelText: '仍然拒绝',
								cancelColor: '#999999',
								success(res) {
									if (res.confirm) {
										console.log('用户点击确定')
										wx.openSetting({
											success(res) {
												
												that.dingyueComfirm(tmplId)
											},
											fail(err) {
												//失败
												console.log(err)
											}
										})
									} else if (res.cancel) {
										console.log('用户点击取消')
									}
								}
							})
						}
					}
				})
			},
			// 订阅信息
			dingyueComfirm: function(tmplId) {
				wx.requestSubscribeMessage({
					tmplIds: [tmplId],
					success: res => {
					},
					fail(err) {
						//失败
						console.log(err)
					}
				})
				// wx.showModal({
				// 	title: '订阅消息',
				// 	content: '请同意我们给您推送信息，以便接受租户提交审核提醒。',
				// 	success: res => {
				// 		if (res.confirm) {
							
				// 		}
				// 	}
				// })
			},
			
			scroll(e) {
				this.scrollTop = top * 2

			},
			daysBetween(date) {
				// 将输入转换为Date对象
				const d1 = new Date();
				const d2 = new Date(date);

				// 计算两个日期的时间戳差值（毫秒）
				const differenceInMilliseconds = Math.abs(d2 - d1);

				// 转换为天数（一天有86400000毫秒）
				const oneDay = 86400000;
				return Math.ceil(differenceInMilliseconds / oneDay); // 返回整数天数，因为Math.ceil向上取整
			},
			Thumbsup() {
				if (!this.token) {
					setTimeout(() => {
						this.$utils.judgeToken()
					}, 500)
					uni.$u.toast('未登录请先登录')
					return
				}
				if (this.isThumbsuped) {
					uni.$u.toast('取消点赞')
					this.thumbsupers = this.thumbsupers.filter(item => item.avatar != uni.getStorageSync('user').avatar)
				} else {
					uni.$u.toast('点赞成功')
					this.thumbsupers.push({
						avatar: uni.getStorageSync('user').avatar
					})
				}
				this.isThumbsuped = !this.isThumbsuped
				this.$api.Thumbsup.Thumbsup('conquer', this.conquer_id)

			},
			changeimage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						res.tempFilePaths.forEach((item, index) => {
							uni.uploadFile({
								url: this.$config.url +
									'/api/conquer/image/upload', //仅为示例，非真实的接口地址
								filePath: item,
								name: 'file',
								formData: {
									'conquer_id': this.conquer_id
								},
								header: {
									'Content-Type': 'application/json;charset=UTF-8',
									'Authorization': "Bearer " + uni.getStorageSync('token')
								},
								success: (res) => {
									this.detail.thumb = item
								},
							});
						})

					},
					fail: () => {

					}
				})
			},
			Followed() {
				if (!this.token) {
					setTimeout(() => {
						this.$utils.judgeToken()
					}, 500)
					uni.$u.toast('未登录请先登录')
					return
				}
				if (this.isFollowed) {
					uni.$u.toast('取消关注')
					this.$api.Followed.DelFollow({
						user_id: this.detail.user_id
					}).then(res => {}).catch(err => {
						uni.$u.toast(err.data.message)
						this.isFollowed = !this.isFollowed
					})
				} else {
					uni.$u.toast('关注成功')
					this.$api.Followed.Follow({
						user_id: this.detail.user_id
					}).then(res => {}).catch(err => {
						uni.$u.toast(err.data.message)
						this.isFollowed = !this.isFollowed
					})
				}
				this.isFollowed = !this.isFollowed

			},

			cancel() {
				if (this.disabled) return
				this.$refs.uForm.resetFields()
				this.form = {
					weight: null,
					motto: null
				}
				this.AttendedAddShow = false
			},
			confirm() {
				if (this.disabled) return
				this.$refs.uForm.validate().then(res => {
					this.disabled = true
					this.$api.Conquer.Add(this.conquer_id, this.form).then(res => {
						uni.$u.toast('加入成功')
						this.disabled = false
						this.isAttended = true
						this.List.push({
							user_id:this.myUser.id,
							user:{
								avatar:this.myUser.avatar,
								nick_name:this.myUser.nick_name
							},
							motto:this.form.motto
						})
						this.cancel()
						this.auditSubscriptionsSetting()
					}).catch(err => {
						this.disabled = false
						uni.$u.toast(err.data.message)
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			attended() {
				if (!this.token) {
					setTimeout(() => {
						this.$utils.judgeToken()
					}, 500)
					uni.$u.toast('未登录请先登录')
					return
				}
				if (this.isAttended) {
					this.isAttended = false
					uni.$u.toast('退出成功')
					this.List = this.List.filter(item => item.user_id != this.myUser.id)
					this.$api.Conquer.UnAdd(this.conquer_id)
					return
				}
				this.AttendedAddShow = true
				setTimeout(() => {
					this.$refs.uForm.setRules(this.rules)
				}, 500)
			},
			jumpUser(id) {
				if (!this.has_started) return
				this.$utils.navigateTo({
					url: '/User/detail?id=' + id + '&conquer_id=' + this.conquer_id
				})
			},
			getDateil(id) {
				uni.showLoading({
					title: '加载中...'
				})
				this.$api.Conquer.Detail(id).then(res => {
					this.isFollowed = res.data.isFollowed
					this.isThumbsuped = res.data.isThumbsuped
					this.detail = res.data.conquer
					this.is_public = this.detail.is_public
					this.has_started = this.detail.has_started
					this.user = res.data.conquer.user
					this.rankList = res.data.activities.data
					this.userList = res.data.activities
					this.isAttended = res.data.isAttended
					this.loading = false
					this.query(1, 10)
				}).catch(err => {
					uni.hideLoading()
				})
			},
			query(page, size) {
				let obj = {
					page,
					size,
					conquer_id: this.conquer_id
				}
				uni.showLoading({
					title: '加载中...'
				})
				this.$api.Conquer.User(this.conquer_id, obj).then(res => {
					this.Listloading = false
					this.$refs.paging.complete(res.data.users.data)
					uni.hideLoading()
				}).catch(err => {
					uni.hideLoading()
				})

			}

		}
	}
</script>

<style lang="scss" scoped>
	.InfoBox {
		margin: 20rpx auto;
		background-color: #fff;
		box-shadow: 0 0 10rpx #ddd;
		padding: 10rpx;
		border-radius: 8rpx;

		.title {
			width: 100%;
			border-bottom: 1rpx solid #ddd;
			margin: 0 0 20rpx;
		}

		.infoContent {
			display: flex;
			width: 100%;
			justify-content: space-between;
		}
	}

	.page {
		height: 100vh;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 10rpx);
		/* 兼容 iOS 设备 */
		padding-bottom: calc(env(safe-area-inset-bottom) + 10rpx);
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
	}

	.stepsBox {
		padding: 0rpx 20rpx;
		height: 100rpx;
		position: absolute;
		z-index: 1;
		display: flex;
		overflow: auto;
	}

	.fff {
		background-color: #fff;
		width: 100%;
		z-index: 111;
	}



	.contentBox {
		padding: 20rpx 0 0 0;
		flex: 1;
		position: relative;
	}

	.background {
		height: 500rpx;
		width: 100%;
		position: relative;
	}

	.masking {
		background: linear-gradient(to top, rgba(0, 0, 0, 0.3), rgba(255, 255, 255, 0), rgba(255, 255, 255, 0));
		position: absolute;
		width: 100%;
		height: 500rpx;
		z-index: 2;
	}

	.backBox {
		position: fixed;
		left: 40rpx;
		z-index: 1111111111;
	}

	.Vr {
		background: rgba(0, 0, 0, 0.3);
		padding: 10rpx 20rpx;
		border-radius: 100rpx;
		color: #fff;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;

		>button {
			opacity: 0;
			position: absolute;
			z-index: 1;
			width: 100%;
			height: 100%;
			top: 0;
			left: 0;
		}
	}

	.VrBox {
		display: flex;
		position: absolute;
		align-items: center;
		z-index: 111;

		>view {
			margin-right: 10rpx;
		}
	}

	.iconfont {
		margin-right: 10rpx;
		font-size: 24rpx;
	}

	.userBox {
		display: flex;
		position: absolute;
		width: 90vw;
		left: 40rpx;
		z-index: 111;
	}

	.radius {
		position: absolute;
		bottom: 0;
		height: 20rpx;
		width: 100vw;
		background-color: #f5f5f5;
		border-radius: 16rpx 16rpx 0 0;
		z-index: 11;
	}

	.bottom {
		position: fixed;
		bottom: 10vh;
		right: 5vw;
		width: 100rpx;
		height: 100rpx;
		background-color: #999;
		border-radius: 16rpx 16rpx 0 0;
		z-index: 11;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 100%;
	}

	.access {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 26rpx;
		text-align: center;
		margin-top: 20rpx;
		margin-right: 20rpx;
		width: 100rpx;
	}

	.rankBox {
		left: 40rpx;
		position: absolute;
		z-index: 1;

		.rankTime {
			color: #fff;
			font-size: 35rpx;
			margin-bottom: 10rpx;
		}


	}

	.Followed {
		margin-bottom: 0;
		z-index: 11111;
		position: absolute;
		left: 40rpx;
		bottom: 40rpx;
		display: flex;
		align-items: center;

		>view {
			margin-right: 10rpx;
			border-radius: 100rpx;
		}
	}

	.startBox {
		font-size: 26rpx;
		color: #fff;
		text-align: right;
	}

	.add {
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50rpx;
		width: 200rpx;
		position: fixed;
		margin: auto;
		left: 0;
		right: 0;
		bottom: calc(constant(safe-area-inset-bottom) + 10rpx);
		/* 兼容 iOS 设备 */
		bottom: calc(env(safe-area-inset-bottom) + 10rpx);
		background: linear-gradient(to top, #3573be, #489aff);
	}
</style>